﻿using System;
using System.Windows.Threading;
using DesignByContract;
using MadMediaManager.WPFSupport.Interfaces.Services;
using MadMediaManager.WPFSupport.Services.Helpers;

namespace MadMediaManager.WPFSupport.Services
{
    public class WeakEventPublisher : IEventPublisher
    {
        private readonly MessageToActionsMap _messageToActionsMap = new MessageToActionsMap();

        public void Publish<T>(T eventToPublish)
        {
            Check.Require(eventToPublish != null, "eventToPublish cannot be null");

            var dispatcher = Dispatcher.CurrentDispatcher;
            var actions = _messageToActionsMap.GetActions<T>();
            if (actions != null)
                actions.ForEach(action => dispatcher.Invoke(action, eventToPublish));
        }

        public void Subscribe<T>(Action<T> action)
        {
            Check.Require(action != null, "action cannot be null");
            _messageToActionsMap.AddAction(action.Target, action.Method, typeof(T));
        }
    }
}
